package com.zhu.controller;

import com.zhu.pojo.entity.Category;
import com.zhu.pojo.entity.Result;
import com.zhu.service.ArticleService;
import com.zhu.service.CategoryService;
import com.zhu.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Tag(name = "文章分类相关")
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleService articleService;

    @Operation(summary = "新增文章分类")
    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        categoryService.add(category);
        return Result.success();
    }

    @Operation(summary = "文章分类列表")
    @GetMapping
    public Result<List<Category>> list() {
        List<Category> cs = categoryService.list();
        return Result.success(cs);
    }

    @Operation(summary = "文章分类详情")
    @GetMapping("/detail")
    public Result<Category> detail(@RequestParam Integer id) {
        Category category = categoryService.findById(id);
        return Result.success(category);
    }

    @Operation(summary = "更新文章分类")
    @PutMapping
    public Result update(@RequestBody @Validated(Category.Update.class) Category category) {
        categoryService.update(category);
        return Result.success("更新成功");
    }

    @Operation(summary = "删除文章分类")
    @DeleteMapping
    public Result delete(@RequestParam Integer id) {
        Category category = categoryService.findById(id);
        if (category == null) {return Result.error(String.format("文章分类 %s 不存在", id));}
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        if (!category.getCreateUser().equals(userId)) {
            return Result.error("用户只能删除由自己创建文章分类");
        }
        Integer articleNum = articleService.findByCategory(id);
        if (articleNum > 0) {
            return Result.error("当前文章分类下存在已创建文章，请先删除文章再删除分类");
        }

        categoryService.delete(id);
        return Result.success("删除成功");
    }
}
